<template>
  <div class="employee">
    <!-- 头部按钮区 -->
    <el-card>
      <el-row type="flex" justify="space-around">
        <el-col>
          <el-alert
            class="tips"
            :closable="false"
            :title="`总数量${total}`"
            type="success"
          />
        </el-col>
        <el-col>
          <el-button type="danger" size="small" @click="exportdata">
            表格普通导出
          </el-button>
          <el-button type="warning" size="small" @click="exportdataTwo">
            表格复杂导出
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="$router.push('/import')"
          >
            Excel导入
          </el-button>
          <el-button type="primary" size="small" @click="showDialog = true">
            新增员工
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table border :data="list">
        <el-table-column label="序号" sortable="" type="index" />
        <el-table-column label="姓名" sortable="" prop="username" />
        <el-table-column label="头像" sortable="" prop="staffPhoto">
          <template v-slot="{ row }">
            <img
              v-imgerr="require('@/assets/common/head.jpg')"
              style="width: 60px; border-radius: 50%"
              :src="row.staffPhoto"
              @click="avaterClick(row.staffPhoto)"
            />
          </template>
        </el-table-column>
        <el-table-column label="手机号" sortable="" prop="mobile" />
        <el-table-column label="工号" sortable="" prop="workNumber" />
        <el-table-column
          label="聘用形式"
          :formatter="formatHire"
          sortable=""
          prop="formOfEmployment"
        />
        <el-table-column label="部门" sortable="" prop="departmentName" />
        <el-table-column
          label="入职时间"
          :formatter="formatTime"
          sortable=""
          prop="timeOfEntry"
        />
        <el-table-column label="账户状态" sortable="" prop="enableState">
          <template v-slot="{ row }">
            <el-switch v-model="row.enableState" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template v-slot="{ row }">
            <el-button
              type="text"
              size="small"
              @click="$router.push(`/employees/detail/${row.id}`)"
            >
              查看
            </el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assign(row)">
              角色
            </el-button>
            <el-button type="text" size="small" @click="del(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          :page-size="page.size"
          layout="prev, pager, next"
          :total="total"
          :current-page="page.page"
          @current-change="changePage"
        />
      </el-row>

      <!-- 添加员工 -->
      <AddEmployee :show-dialog="showDialog" @close="close" />

      <!-- 给员工分配角色弹层 -->
      <AssignRole
        :id="id"
        ref="role"
        :assign-role-pup.sync="assignRolePup"
        @close="assignRolePup = false"
      />
    </el-card>

    <!-- 二维吗弹层 -->
    <el-dialog :visible="codeDialog" @close="codeDialog = false">
      <canvas ref="myCanvas"></canvas>
    </el-dialog>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
import AddEmployee from './components/add-employee.vue'
import Enum from '@/api/constant/employees'
import moment from 'moment'
import { employeeList, delEmployee } from '@/api/employee'
export default {
  name: 'EmloyeeIndex',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      Enum,
      total: 0,
      list: [],
      page: {
        page: 1,
        size: 10
      },
      showDialog: false,
      assignRolePup: false,
      id: '',
      codeDialog: false
    }
  },
  created() {
    this.employeeList()
  },
  methods: {
    // 获取员工列表
    async employeeList() {
      const res = await employeeList(this.page)
      this.list = res.rows
      this.total = res.total
    },
    // 页码改变
    changePage(currentPage) {
      this.page.page = currentPage
      this.employeeList()
    },
    a(row) {
      console.log(row)
    },
    // 格式化时间
    formatTime(row) {
      return moment(row.timeOfEntry).format('YYYY-MM-DD')
    },
    // 格式化聘用形式
    formatHire(row) {
      this.Enum.hireType.forEach((item) => {
        if (item.id === row.formOfEmployment) {
          return item.value
        }
      })
      return '未知'
    },
    // 删除角色
    del(id) {
      this.$confirm('是否确定删除该角色', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delEmployee(id)
          this.$message('删除成功')
          this.employeeList()
        } catch (err) {
          this.$message('删除失败')
        }
      })
    },
    // 关闭添加弹层
    close() {
      this.showDialog = false
      this.employeeList()
    },
    // 分配角色按钮点击
    assign(row) {
      this.id = row.id
      this.assignRolePup = true
      this.$refs.role.getEmployeeBaseInfo(row.id)
    },
    // 普通表格导出
    exportdata() {
      import('@/vendor/Export2Excel').then(async (excel) => {
        const { rows } = await employeeList({ page: 1, size: 10000 })
        const headers = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const data = this.formatJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工表'
        })
      })
    },
    // 复杂表格导出
    exportdataTwo() {
      import('@/vendor/Export2Excel').then(async (excel) => {
        const { rows } = await employeeList({ page: 1, size: 10000 })
        const headers = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const data = this.formatJson(headers, rows)
        excel.export_json_to_excel({
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']], // 复杂表头,可不写
          merges: ['A1:A2', 'B1:F1', 'G1:G2'], // 和复杂表头配合使用  merges, multiHeader可以不用
          header: Object.keys(headers),
          data: data,
          filename: '员工表',
          bookType: 'xlsx'
        })
      })
    },
    // 格式化表单数据
    formatJson(header, rows) {
      return rows.map((item) => {
        return Object.keys(header).map((key) => {
          if (
            header[key] === 'timeOfEntry' ||
            header[key] === 'correctionTime'
          ) {
            return moment(item[header[key]]).format('YYYY-MM-DD')
          }
          return item[header[key]]
        })
      })
    },
    // 点击头像显示二维吗
    avaterClick(img) {
      if (img) {
        this.codeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, img, {
            width: '200px',
            height: '200px'
          })
        })
      } else {
        this.$message('该用户未上传头像')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.employee {
  font-size: 16px;
  padding: 20px;
  .tips {
    width: 180px;
  }
}
</style>
